﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GRWL.BZSC.UI.BaseDataSvc;
using GRWL.BZSC.UI.CustomCtrl;
using UserCtrl;
//using GRWL.BZSC.Common;

namespace GRWL.BZSC.UI
{
    public partial class DepotInOutFrm : BaseFrm
    {
        ///// <summary>
        ///// 记住当前设置的编码规则
        ///// </summary>
        //public CodeRuleFrm.CodeRule codeRule { get; set; }

        //// 单据编辑状态
        //public GRWL.BZSC.UI.Common.BillOperateType EditStatus;

        //public enum DepotIOStatus
        //{
        //    /// <summary>
        //    /// 经采购（含质检）后收货入库操作
        //    /// </summary>
        //    采购收货,
        //    /// <summary>
        //    /// 经生产（含质检）环节后收货
        //    /// </summary>
        //    生产收货,
        //    /// <summary>
        //    /// 出库操作
        //    /// </summary>
        //    出库,
        //    /// <summary>
        //    /// 调拨操作
        //    /// </summary>
        //    调拨,
        //    /// <summary>
        //    /// 数量调整操作
        //    /// </summary>
        //    数量调整,
        //    /// <summary>
        //    /// 库位调整操作
        //    /// </summary>
        //    库位调整
        //}

        public GRWL.BZSC.Common.EnumCommon.DepotIOStatus IOStatus { get; set; }

        ////单据编号字头
        //private string BillPrefix;

        //private TB_Shipping tbShipping;
        //private TB_ShippingDetail[] tbShippingDetail;
        private XShipping xMain;
        private XShippingDetial[] xDetials;

        private TB_Trader Trader;
        private TB_Department Department;
        //private TB_Department[] Departments;

        //private TB_User[] Users;
        private XUser[] XUsers;

        bool bEdit, bConfirm, bPrint;

        public DepotInOutFrm()
        {
            InitializeComponent();

            this.BaseDataProxy = new BaseDataClient();
            this.BaseDataProxy.Open();

            this.codeRule = new CodeRuleFrm.CodeRule();

            EditStatus = Common.BillOperateType.None;

            IOStatus = GRWL.BZSC.Common.EnumCommon.DepotIOStatus.采购收货;
            this.Text = "收货单";
            //BillPrefix = "CGSH";
        }

        private void DepotInFrm_Load(object sender, EventArgs e)
        {
            DisabledControls();
            //Departments = BaseDataProxy.FindDepartments(null);

            // Attach DataGridView events to the corresponding event handlers.
            //gvDetail.CellValidating += new
            //    DataGridViewCellValidatingEventHandler(gvDetail_CellValidating);
            //gvDetail.CellEndEdit += new
            //    DataGridViewCellEventHandler(gvDetail_CellEndEdit);
            //gvDetail.CellContentDoubleClick += new DataGridViewCellEventHandler(gvDetail_CellContentDoubleClick);
            gvDetail.CellDoubleClick += new DataGridViewCellEventHandler(gvDetail_CellDoubleClick);
            gvDetail.RowsAdded += new DataGridViewRowsAddedEventHandler(gvDetail_RowsAdded);
            gvDetail.RowsRemoved += new DataGridViewRowsRemovedEventHandler(gvDetail_RowsRemoved);
            gvDetail.CellFormatting += new DataGridViewCellFormattingEventHandler(gvDetail_CellFormatting);

            if (IOStatus == GRWL.BZSC.Common.EnumCommon.DepotIOStatus.采购收货)
            {
                this.Text = IOStatus.ToString() + "单";
                BillPrefix = GRWL.BZSC.Common.EnumCommon.BillType.CGSH.ToString();
            }
            if (IOStatus == GRWL.BZSC.Common.EnumCommon.DepotIOStatus.生产收货)
            {
                this.Text = IOStatus.ToString() + "单";
                BillPrefix = GRWL.BZSC.Common.EnumCommon.BillType.SCSH.ToString();
            }
            if (IOStatus == GRWL.BZSC.Common.EnumCommon.DepotIOStatus.出库)
            {
                this.Text = "出库单";
                BillPrefix = GRWL.BZSC.Common.EnumCommon.BillType.CK.ToString(); //"CK";
            }
            Name = BillPrefix;
        }

        private void SetControlsData()
        {
            edtBillCode.Text = tMain.Rows[0]["code"].ToString();
            string strDayTime = tMain.Rows[0]["createTime"].ToString();
            string sShippingDate = tMain.Rows[0]["shippingDate"].ToString();
            if (!String.IsNullOrEmpty(sShippingDate))
                edtBillDate.Value = Convert.ToDateTime(sShippingDate);
            edtOperator.Text = tMain.Rows[0]["OperatorName"].ToString();
            edtAssessor.Text = tMain.Rows[0]["AssessorName"].ToString();
            edtBillStatus.Text = tMain.Rows[0]["status"].ToString();
            //traderSelector
            addressUTextBox.Text = tMain.Rows[0]["address"].ToString();
            //departmentUTextBox
            edtBusinessman.Text = tMain.Rows[0]["BusinessName"].ToString();
            edtMemo.Text = tMain.Rows[0]["memo"].ToString();
            edtMender.Text = tMain.Rows[0]["MenderName"].ToString();
            edtType.Text = tMain.Rows[0]["type"].ToString();

            strDayTime = tMain.Rows[0]["updateTime"].ToString();
            if (!String.IsNullOrEmpty(strDayTime))
                edtUpdateTime.Value = Convert.ToDateTime(strDayTime);
            strDayTime = tMain.Rows[0]["verifyTime"].ToString();
            if (!String.IsNullOrEmpty(strDayTime))
                edtVerifyTime.Value = Convert.ToDateTime(strDayTime);

            if (!string.IsNullOrEmpty(tMain.Rows[0]["trader"].ToString()))
            {
                SelectItem item = new SelectItem();
                Trader = BaseDataProxy.GetTrader((int)tMain.Rows[0]["trader"]);
                if (Trader != null)
                {
                    item.Name = Trader.name;
                    item.Key = Trader.code;
                    item.Value = Trader.id.ToString();
                    edtTrader.SetSelected(item);
                }
            }

            if (!string.IsNullOrEmpty(tMain.Rows[0]["department"].ToString()))
            {
                SelectItem item = new SelectItem();
                Department = BaseDataProxy.GetDepartment((int)tMain.Rows[0]["department"]);
                if (Department != null)
                {
                    item.Name = Department.name;
                    item.Key = Department.code;
                    item.Value = Department.id.ToString();
                    departmentUTextBox.SetSelected(item);
                }
            }

            UpdateBizManList(Common.StringToInt(tMain.Rows[0]["department"].ToString()));

            gvDetail.SuspendLayout();
            gvDetail.DataSource = tDetail;
            //gvDetail.AutoResizeColumns();
            gvDetail.ResumeLayout();
        }

        private bool GetControlsData()
        {
            //tMain.Rows[0]["code"] = edtBillCode.Text;
            tMain.Rows[0]["shippingDate"] = edtBillDate.Value;
            //tMain.Rows[0]["createTime"] = edtBillDate.Value;
            tMain.Rows[0]["OperatorName"] = edtOperator.Text;
            tMain.Rows[0]["AssessorName"] = edtAssessor.Text;
            tMain.Rows[0]["status"] = edtBillStatus.Text;
            //traderSelector
            tMain.Rows[0]["address"] = addressUTextBox.Text;
            //departmentUTextBox
            //tMain.Rows[0]["BusinessName"] = edtBusinessman.Text;
            if (edtBusinessman.SelectedItem == null)
            {
                tMain.Rows[0]["businessman"] = DBNull.Value;
                tMain.Rows[0]["BusinessName"] = "";
            }
            else
            {
                tMain.Rows[0]["businessman"] = ((TB_User)edtBusinessman.SelectedItem).id;
                tMain.Rows[0]["BusinessName"] = ((TB_User)edtBusinessman.SelectedItem).name;
            }

            tMain.Rows[0]["memo"] = edtMemo.Text;
            tMain.Rows[0]["MenderName"] = edtMender.Text;
            //tMain.Rows[0]["updateTime"] = updateTimeUDateTimePicker.Value;

            //if (EditStatus == Common.BillOperateType.Add)
            //{
            //    tMain.Rows[0]["operator"] = SysLoginUserInfo.UserId;
            //    tMain.Rows[0]["OperatorName"] = SysLoginUserInfo.UserName;
            //    tMain.Rows[0]["createTime"] = DateTime.Now;
            //    tMain.Rows[0]["status"] = "未批";
            //}
            //else
            //{
            //    tMain.Rows[0]["mender"] = SysLoginUserInfo.UserId;
            //    tMain.Rows[0]["MenderName"] = SysLoginUserInfo.UserName;
            //    tMain.Rows[0]["updateTime"] = DateTime.Now;
            //}
            edtOperator.Text = tMain.Rows[0]["OperatorName"].ToString();
            edtMender.Text = tMain.Rows[0]["MenderName"].ToString();

            if (gvDetail.Rows.Count == 0)
            {
                MessageBox.Show("单据明细记录为空不可以保存。");
                return false;
            }

            foreach (DataGridViewRow TheRow in gvDetail.Rows)
            {
                if ((string.IsNullOrEmpty(TheRow.Cells["clMaterialId"].Value.ToString())) || (string.IsNullOrEmpty(TheRow.Cells["clMaterialCode"].Value.ToString())))
                {
                    gvDetail.CurrentCell = TheRow.Cells["clMaterialCode"];
                    MessageBox.Show("输入的物资不正确，请重新输入。");
                    return false;
                }
            }
            return true;
        }

        void gvDetail_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            Common.CellFormatColor(sender, e, EditStatus);
        }

        void gvDetail_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            Common.ShowDataGridViewRowNo((UDataGridView)sender);

        }

        void gvDetail_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            Common.ShowDataGridViewRowNo((UDataGridView)sender);

        }

        private void gvDetail_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            if ((EditStatus != Common.BillOperateType.Add) & (EditStatus != Common.BillOperateType.Update))
            {
                return;
            }

            // Validate the CompanyName entry by disallowing empty strings.
            if (gvDetail.Columns[e.ColumnIndex].Name == "clDepotCode") //仓库编号
            {
                if (String.IsNullOrEmpty(e.FormattedValue.ToString()))
                {
                    //gvDetail.Rows[e.RowIndex].ErrorText = "仓库编号不可为空。";
                    DepotFrm frm = new DepotFrm();
                    frm.Text = "选择仓库";
                    frm.SearchMode();
                    if (frm.ShowDialog() == DialogResult.OK)
                    {
                        gvDetail.CurrentRow.Cells["clDepotName"].Value = frm.SelectorItem.Name;
                        gvDetail.CurrentRow.Cells["clDepotId"].Value = frm.SelectorItem.Key;
                        //gvDetail.CurrentRow.Cells["clDepotCode"].Value = frm.SelectorItem.Value;
                        e.Cancel = false;
                    }
                    else
                        e.Cancel = true;
                }
            }
        }

        private void gvDetail_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex < 0)
                return;

            if ((EditStatus != Common.BillOperateType.Add) & (EditStatus != Common.BillOperateType.Update))
            {
                return;
            }

            UDataGridView TheView = (UDataGridView)sender;
            DataGridViewRow TheRow = TheView.CurrentRow; //gvDetail.CurrentRow .Rows[e.RowIndex]
            DataGridViewColumn TheCol = TheView.Columns[e.ColumnIndex]; //gvDetail.Columns[e.ColumnIndex]

            //物资编号
            if ((TheCol.Name == "clMaterialCode") | (TheCol.Name == "clMaterialName"))
            {
                FindMaterialFrm frm = new FindMaterialFrm();
                frm.Text = "选择物资";
                if (frm.ShowDialog() == DialogResult.OK)
                {
                    TheRow.Cells["clMaterialName"].Value = frm.SelectorItem.CnName;
                    TheRow.Cells["clMaterialId"].Value = frm.SelectorItem.Id;
                    TheRow.Cells["clMaterialCode"].Value = frm.SelectorItem.Code;
                    TheRow.Cells["Specs"].Value = frm.SelectorItem.Specs;
                    TheRow.Cells["Unit"].Value = frm.SelectorItem.Unit;
                }
            }
            //仓库编号
            if ((TheCol.Name == "clDepotCode") | (TheCol.Name == "clDepotName"))
            {
                DepotFrm frm = new DepotFrm();
                frm.Text = "选择仓库";
                frm.SearchMode();
                if (frm.ShowDialog() == DialogResult.OK)
                {
                    //TheRow.Cells["clDepotName"].Value = frm.SelectorItem.Name;
                    //TheRow.Cells["clDepotId"].Value = frm.SelectorItem.Value;
                    //TheRow.Cells["clDepotCode"].Value = frm.SelectorItem.Key;

                    ReplaceDepot(TheRow, frm.SelectorItem.Value, frm.SelectorItem.Key, frm.SelectorItem.Name);
                    if (e.RowIndex == (TheView.Rows.Count - 1))
                        return;

                    string message = "是否替换剩下的所有仓库？";
                    string caption = "确认";
                    MessageBoxButtons buttons = MessageBoxButtons.YesNo;
                    DialogResult result = MessageBox.Show(message, caption, buttons);
                    if (result == DialogResult.Yes)
                    {
                        foreach (DataGridViewRow gvRow in TheView.Rows)
                        {
                            if (gvRow.Index < TheRow.Index)
                                continue;
                            ReplaceDepot(gvRow, frm.SelectorItem.Value, frm.SelectorItem.Key, frm.SelectorItem.Name);
                        }
                    }

                }
            }
        }

        private void ReplaceDepot(DataGridViewRow TheRow, string DepotId, string DepotCode, string DepotName)
        {
            TheRow.Cells["clDepotName"].Value = DepotName;
            TheRow.Cells["clDepotId"].Value = DepotId;
            TheRow.Cells["clDepotCode"].Value = DepotCode;
        }

        /// <summary>
        /// 重写继承窗体中编辑状态转换后的处理代码
        /// </summary> 
        public override void EditStatusChanged()
        {
            RefreshStatus();
            //btnAppend.Enabled = (EditStatus != Common.BillOperateType.Add) && (EditStatus != Common.BillOperateType.Update);
            //btnOpen.Enabled = (EditStatus == Common.BillOperateType.None);
            btnSave.Enabled = bEdit;
            btnSelect.Enabled = bEdit;
            btnDelete.Enabled = bEdit;
            btnAddItem.Enabled = bEdit;
            btnDelItem.Enabled = bEdit;
            btnConfirm.Enabled = bConfirm;
            btnPrint.Enabled = bPrint;
        }

        private void RefreshStatus()
        {
            bEdit = (EditStatus == Common.BillOperateType.Add) || (EditStatus == Common.BillOperateType.Update);
            bConfirm = (tMain.Rows.Count > 0);
            if (bConfirm)
                bConfirm = (Common.StringToInt(tMain.Rows[0]["id"].ToString()) > 0);
            bPrint = (EditStatus != Common.BillOperateType.Add) && (EditStatus != Common.BillOperateType.Update);
        }

        private void DisabledControls()
        {
            SetControlsStatus(false);
        }

        private void EnabledControls()
        {
            SetControlsStatus(true);
        }

        private void SetControlsStatus(bool SetEnagledFlag)
        {
            //edtBillCode.Enabled = SetEnagledFlag;
            edtBillDate.Enabled = SetEnagledFlag;
            edtOperator.Enabled = SetEnagledFlag;
            edtAssessor.Enabled = SetEnagledFlag;
            edtBillStatus.Enabled = SetEnagledFlag;
            edtTrader.Enabled = SetEnagledFlag;
            addressUTextBox.Enabled = SetEnagledFlag;
            departmentUTextBox.Enabled = SetEnagledFlag;
            edtBusinessman.Enabled = SetEnagledFlag;
            edtMemo.Enabled = SetEnagledFlag;
            edtMender.Enabled = SetEnagledFlag;
            //edtUpdateTime.Enabled = SetEnagledFlag;
            //verifyTimeUDateTimePicker.Enabled = SetEnagledFlag;

            gvDetail.ReadOnly = !SetEnagledFlag;
            if (!gvDetail.ReadOnly)
            {
                gvDetail.Columns["clMaterialName"].ReadOnly = true;
                gvDetail.Columns["Specs"].ReadOnly = true;
                gvDetail.Columns["Unit"].ReadOnly = true;
                gvDetail.Columns["clDepotName"].ReadOnly = true;
                gvDetail.Columns["clOrderCode"].ReadOnly = true;
                gvDetail.Columns["prevCode"].ReadOnly = true;
            }
        }

        private void btnAppend_Click(object sender, EventArgs e)
        {
            //放弃新单
            //if (EditStatus == Common.BillOperateType.Add)
            //{
            //    EditStatus = Common.BillOperateType.None;
            //    SetControlsStatus(false);
            //    gvDetail.CancelEdit();
            //    return;
            //}

            //新单输入
            EditStatus = Common.BillOperateType.Add;
            SetControlsStatus(true);

            tMain.Clear();
            DataRow NewMainRow = tMain.NewRow();
            // 开新单时，单号为空，保存时申请后显示
            NewMainRow["code"] = ""; //BaseDataProxy.GetSerialNo(1, BillPrefix, 4,true, true, true);
            NewMainRow["operator"] = SysLoginUserInfo.UserId;
            //NewMainRow["OperatorCode"] = SysLoginUserInfo.UserCode;
            NewMainRow["OperatorName"] = SysLoginUserInfo.UserName;
            NewMainRow["createTime"] = DateTime.Now;
            NewMainRow["type"] = IOStatus.ToString(); // BillPrefix;
            NewMainRow["isVerify"] = false;
            NewMainRow["isClosed"] = false;
            NewMainRow["isCheck"] = false;
            NewMainRow["status"] = "未批";
            tMain.Rows.Add(NewMainRow);

            tDetail.Clear();
            DataRow NewDetailRow = tDetail.NewRow();
            tDetail.Rows.Add(NewDetailRow);

            SetControlsData();
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            //SelectBillFrm frm = new SelectBillFrm();
            ////frm.SetCondition(GRWL.BZSC.Common.EnumCommon.BillType.CGSH, BillPrefix, false);
            //if (IOStatus == GRWL.BZSC.Common.EnumCommon.DepotIOStatus.采购收货)
            //{
            //    frm.SetCondition(GRWL.BZSC.Common.EnumCommon.BillType.CGSH, BillPrefix, false);
            //}
            //if (IOStatus == GRWL.BZSC.Common.EnumCommon.DepotIOStatus.生产收货)
            //{
            //    frm.SetCondition(GRWL.BZSC.Common.EnumCommon.BillType.SCSH, BillPrefix, false);
            //}
            //if (IOStatus == GRWL.BZSC.Common.EnumCommon.DepotIOStatus.出库)
            //{
            //    frm.SetCondition(GRWL.BZSC.Common.EnumCommon.BillType.CK, BillPrefix, false);
            //}
            //frm.ShowDialog();

            FindBillFrm frm = new FindBillFrm();
            frm.AllowMulitSelect = false;
            frm.SelectBillType = GRWL.BZSC.Common.EnumCommon.BillType.CGSH;
            frm.SearchMode = GRWL.BZSC.UI.FindBillFrm.SearchModeType.open;

            frm.Text = "打开收货单";

            if (frm.ShowDialog() == DialogResult.OK)
            {
                if (frm.SelectedItems != null)
                {
                    QShipping qsh = OTConverter.ConvertToObject<QShipping>(frm.SelectedItems);
                    OpenBill(qsh.Id);
                }
            }
        }

        private void OpenBill(int BillId)
        {
            xMain = BaseDataProxy.GetXShipping(BillId);
            xDetials = BaseDataProxy.GetShippingDetails(BillId);
            if (xMain != null)
            {
                //表头内容
                IEnumerable<XShipping> ary = new List<XShipping>() { xMain };
                tMain = ary.ConvertToDataTable<TB_Shipping>();

                if (xDetials != null)
                {
                    //表体内容
                    tDetail = xDetials.ConvertToDataTable<TB_ShippingDetail>();
                }

                //if (!string.IsNullOrEmpty(tMain.Rows[0]["assessor"].ToString()))
                if ((bool)tMain.Rows[0]["isVerify"] == true)
                {
                    //审批后,不允许再修改
                    EditStatus = Common.BillOperateType.View;
                    SetControlsStatus(false);
                }
                else
                {
                    //未审批,允许再修改
                    tMain.Rows[0]["mender"] = SysLoginUserInfo.UserId;
                    tMain.Rows[0]["MenderName"] = SysLoginUserInfo.UserName;
                    tMain.Rows[0]["updateTime"] = DateTime.Now;
                    EditStatus = Common.BillOperateType.Update;
                    SetControlsStatus(true);
                }
                SetControlsData();
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if ((EditStatus != Common.BillOperateType.Add) & (EditStatus != Common.BillOperateType.Update) & (EditStatus != Common.BillOperateType.Delete))
                return;

            //保存修改
            if (!GetControlsData())
                return;
            if ((EditStatus == Common.BillOperateType.Add) && string.IsNullOrEmpty(tMain.Rows[0]["code"].ToString()))
            {
                tMain.Rows[0]["code"] = BaseDataProxy.GetSerialNo(1, BillPrefix, 4, true, true, true);
                edtBillCode.Text = tMain.Rows[0]["code"].ToString();
            }
            tMain.AcceptChanges();

            foreach (DataRow dr in tDetail.Rows)
            {
                if ((string.IsNullOrEmpty(dr["shippingCode"].ToString()))) //(dr.RowState!=) ||
                    dr["shippingCode"] = tMain.Rows[0]["code"];
            }
            tDetail.AcceptChanges();

            //将 DataTable 转换为写入后台格式 TB_xxxxx
            TB_Shipping tbShipping = OTConverter.ConvertToObject<TB_Shipping>(tMain.Rows[0]);
            List<TB_ShippingDetail> lsShippingDetails = OTConverter.ConvertTableToObject<TB_ShippingDetail>(tDetail);
            TB_ShippingDetail[] tbShippingDetails = lsShippingDetails.ToArray();

            //保存方法，支持主/细单一次写入到后台。
            tbShipping.TB_ShippingDetail = tbShippingDetails;

            int iAddID = -1;
            bool bUpdate = false;

            if (EditStatus == Common.BillOperateType.Add)
            {
                iAddID = BaseDataProxy.AddShipping(tbShipping);
                tMain.Rows[0]["id"] = iAddID;
            }
            else // (EditStatus == Common.BillOperateType.Update)
            {
                bUpdate = BaseDataProxy.UpdateShipping(tbShipping, true);
            }

            if (((EditStatus == Common.BillOperateType.Add) && (iAddID > 0)) || ((EditStatus == Common.BillOperateType.Update) && (bUpdate)))
            {
                MessageBox.Show("已成功保存单据.");
                EditStatus = Common.BillOperateType.Update;
                OpenBill(Common.StringToInt(tMain.Rows[0]["id"].ToString()));
                //SetControlsStatus(false);
            }
            else
                MessageBox.Show("保存单据失败.");

        }

        private void ImportBill(List<SelectBillFrm.SelectBillsInfo> list)
        {
            //
        }

        private void btnSelect_ButtonClick(object sender, EventArgs e)
        {
            btnSelect.ShowDropDown();

        }

        private void btnSelectOrder_Click(object sender, EventArgs e)
        {
            //SelectBillFrm frm = new SelectBillFrm();
            //暂时只允许选择一张单返回
            //frm.SetCondition(GRWL.BZSC.Common.EnumCommon.BillType.CG, "CG", false);

            FindBillFrm frm = new FindBillFrm();
            frm.AllowMulitSelect = false;
            frm.SelectBillType = GRWL.BZSC.Common.EnumCommon.BillType.CG;
            frm.Text = "选单(来自采购单)";
            frm.status = "已批";

            if(frm.ShowDialog() == DialogResult.OK)
            //if (frm.SelectBills.Count > 0)
                if (frm.SelectedItems != null)
                {
                    QOrder qo = OTConverter.ConvertToObject<QOrder>(frm.SelectedItems);
                    //int iBillId = frm.SelectBills[0].BillId;
                    int iBillId = qo.Id;

                    XOrder xImportOrder = BaseDataProxy.GetXOrder(iBillId);
                    if (xImportOrder != null)
                    {
                        SelectItem item = new SelectItem();
                        Trader = BaseDataProxy.GetTrader((int)xImportOrder.Order.trader);
                        if (Trader != null)
                        {
                            item.Name = Trader.name;
                            item.Key = Trader.code;
                            item.Value = Trader.id.ToString();
                            edtTrader.SetSelected(item);
                        }
                        edtMemo.Text = xImportOrder.Order.memo;
                        tMain.Rows[0]["trader"] = Trader.id;
                        //tMain.Rows[0]["TraderCode"] = Trader.code;
                        //tMain.Rows[0]["TraderName"] = Trader.name;
                        tMain.Rows[0]["memo"] = xImportOrder.Order.memo;
                    }

                    XOrderDetail[] xImportDetails = BaseDataProxy.GetXOrderDetails(iBillId);
                    if ((xImportDetails != null) && (xImportDetails.Count() > 0))
                    {
                        foreach (XOrderDetail tbItem in xImportDetails)
                        {
                            DataRow dr = tDetail.NewRow();
                            dr["shipping"] = tMain.Rows[0]["id"];
                            dr["shippingCode"] = tMain.Rows[0]["code"];
                            dr["order"] = iBillId;
                            dr["orderDetailId"] = tbItem.OrderDetail.id;
                            dr["orderCode"] = tbItem.OrderDetail.orderCode;
                            dr["material"] = tbItem.OrderDetail.material;
                            dr["MaterialCode"] = tbItem.OrderDetail.materialCode;
                            dr["MaterialName"] = tbItem.MaterialName;
                            dr["Specs"] = tbItem.Specs;
                            dr["Unit"] = tbItem.Unit;
                            dr["batchNo"] = tbItem.OrderDetail.batchNo;
                            dr["prevId"] = tbItem.OrderDetail.id;
                            dr["prevCode"] = tbItem.OrderDetail.orderCode;
                            dr["prevType"] = BZSC.Common.EnumCommon.BillType.CG.ToString();
                            //订货单中未入库数量
                            decimal num = Common.StringToDecimal(tbItem.OrderDetail.num.ToString());
                            decimal finishedNum = Common.StringToDecimal(tbItem.OrderDetail.finishedNum.ToString());
                            dr["shippingNum"] = num - finishedNum;
                            tDetail.Rows.Add(dr);
                        }
                    }

                    //EditStatus = Common.BillOperateType.Update;
                }

        }

        private void btnSelectProductionQC_Click(object sender, EventArgs e)
        {
            ImportQC(GRWL.BZSC.Common.EnumCommon.BillType.SCZJ);
        }

        private void btnSelectQC_Click(object sender, EventArgs e)
        {
            ImportQC(GRWL.BZSC.Common.EnumCommon.BillType.CGZJ);
        }

        private void ImportQC(GRWL.BZSC.Common.EnumCommon.BillType TheType)
        {
            //SelectBillFrm frm = new SelectBillFrm();
            ////暂时只允许选择一张单返回
            //frm.SetCondition(TheType, TheType.ToString(), false);
            //frm.ShowDialog();

            FindBillFrm frm = new FindBillFrm();
            frm.AllowMulitSelect = false;
            frm.SelectBillType = TheType;
            frm.SearchMode = GRWL.BZSC.UI.FindBillFrm.SearchModeType.source;
            frm.status = "已批";

            if (TheType == GRWL.BZSC.Common.EnumCommon.BillType.SCZJ)
                frm.Text = "单据查找(来自生产质检)";
            if (TheType == GRWL.BZSC.Common.EnumCommon.BillType.CGZJ)
                frm.Text = "单据查找(来自采购质检)";

            //if (frm.SelectBills.Count > 0)
            if(frm.ShowDialog() == DialogResult.OK)
            {
                QQC qc=OTConverter.ConvertToObject<QQC>(frm.SelectedItems);
                //int iBillId = frm.SelectBills[0].BillId;
                int iBillId = qc.Id;
                XQC xImportOrder = BaseDataProxy.GetXQC(iBillId);
                if (xImportOrder != null)
                {
                    SelectItem item = new SelectItem();
                    item.Name = xImportOrder.TraderName;
                    item.Key = xImportOrder.TraderCode;
                    item.Value = xImportOrder.QC.trader.ToString();
                    edtTrader.SetSelected(item);
                    edtMemo.Text = xImportOrder.QC.memo;
                    tMain.Rows[0]["trader"] = xImportOrder.QC.trader;
                    //tMain.Rows[0]["TraderCode"] = xImportOrder.TraderCode;
                    //tMain.Rows[0]["TraderName"] = xImportOrder.TraderName;
                    tMain.Rows[0]["memo"] = xImportOrder.QC.memo;
                }

                XQCDetail[] xImportDetails = BaseDataProxy.GetXQCDetials(iBillId);
                if ((xImportDetails != null) && (xImportDetails.Count() > 0))
                {
                    foreach (XQCDetail tbItem in xImportDetails)
                    {
                        DataRow dr = tDetail.NewRow();
                        dr["shipping"] = tMain.Rows[0]["id"];
                        dr["shippingCode"] = tMain.Rows[0]["code"];
                        dr["order"] = tbItem.QCDetail.prevId;
                        dr["orderDetailId"] = tbItem.QCDetail.id;
                        dr["orderCode"] = tbItem.QCDetail.prevCode;
                        //dr["prevId"] = tbItem.QCDetail.qc;
                        ////dr["prevType"] = tbItem.QCDetail;
                        //dr["prevCode"] = tbItem.QCDetail.qcCode;
                        dr["material"] = tbItem.QCDetail.material;
                        dr["MaterialCode"] = tbItem.QCDetail.materialCode;
                        dr["MaterialName"] = tbItem.MaterialName;
                        dr["Specs"] = tbItem.QCDetail.specs;
                        dr["Unit"] = tbItem.Unit;
                        //质检单中未入库数量
                        decimal notInNum = Common.StringToDecimal(tbItem.QCDetail.notInNum.ToString());
                        dr["shippingNum"] = notInNum;
                        dr["prevId"] = tbItem.QCDetail.id;
                        dr["prevCode"] = tbItem.QCDetail.qcCode;
                        dr["prevType"] = TheType.ToString();

                        tDetail.Rows.Add(dr);
                    }
                }
                //EditStatus = Common.BillOperateType.Update;
            }

        }

        private void btnSelect_Click(object sender, EventArgs e)
        {
            //SelectBillFrm frm = new SelectBillFrm();
            //frm.SetCondition(GRWL.BZSC.Common.EnumCommon.BillType.ZS, BillPrefix, true);
            //frm.ShowDialog();

            //ImportBill(frm.SelectBills);
            //SelectBillFrm.SelectBillsInfo[] sbs = frm.SelectBills;
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            //if (!string.IsNullOrEmpty(tMain.Rows[0]["assessor"].ToString()))
            if ((bool)tMain.Rows[0]["isVerify"] == true)
            {
                MessageBox.Show("无法删除已审批单据.");
                return;
            }

            if ((EditStatus != Common.BillOperateType.Add) & (EditStatus != Common.BillOperateType.Update))
                return;

            //gvDetail.CancelEdit();

            //if (EditStatus == Common.BillOperateType.Add)
            //{
            //    tMain.Rows.Clear();
            //    tDetail.Rows.Clear();
            //    return;
            //}

            //(EditStatus == Common.BillOperateType.Update)
            //if (tMain.Rows[0]["id"] == null)
            //    return;

            int BillId = Common.StringToInt(tMain.Rows[0]["id"].ToString());
            string message = "是否删除单据？";
            string caption = "确认";
            MessageBoxButtons buttons = MessageBoxButtons.YesNo;
            DialogResult result = MessageBox.Show(message, caption, buttons);
            if (result != DialogResult.Yes)
                return;

            if (BaseDataProxy.DeleteShipping(BillId))
            {
                MessageBox.Show("已成功删除单据.");
                EditStatus = Common.BillOperateType.View;
            }
            else
                MessageBox.Show("无法删除单据.");

        }

        private void btnAddItem_Click(object sender, EventArgs e)
        {
            //            gvDetail.Rows.Add();
            DataRow NewDetailRow = tDetail.NewRow();
            if (EditStatus == Common.BillOperateType.Update)
            {
                NewDetailRow["shipping"] = tMain.Rows[0]["id"];
                NewDetailRow["shippingCode"] = tMain.Rows[0]["code"];
                Common.StringToInt(tMain.Rows[0]["id"].ToString());
            }
            tDetail.Rows.Add(NewDetailRow);
        }

        private void btnDelItem_Click(object sender, EventArgs e)
        {
            //
            if (gvDetail.RowCount > 0)
            {
                gvDetail.Rows.RemoveAt(gvDetail.CurrentRow.Index);
                tDetail.AcceptChanges();
                // 删除所有记录后，自动建立一个空白记录
                if (gvDetail.RowCount == 0)
                {
                    btnAddItem_Click(null, null);
                    tDetail.AcceptChanges();
                }
            }
        }

        private void UpdateStatus(int BillId)
        {
            XShipping xMain = BaseDataProxy.GetXShipping(BillId);
            if (xMain != null)
            {
                if (xMain.Shipping.assessor == null)
                    tMain.Rows[0]["assessor"] = DBNull.Value;
                else
                    tMain.Rows[0]["assessor"] = xMain.Shipping.assessor;
                if (xMain.Shipping.verifyTime == null)
                    tMain.Rows[0]["verifyTime"] = DBNull.Value;
                else
                    tMain.Rows[0]["verifyTime"] = xMain.Shipping.verifyTime;
                tMain.Rows[0]["status"] = xMain.Shipping.status;
                tMain.Rows[0]["AssessorName"] = xMain.AssessorName;
                tMain.AcceptChanges();

                edtAssessor.Text = xMain.AssessorName;
                edtVerifyTime.Text = xMain.Shipping.verifyTime.ToString();
                edtBillStatus.Text = xMain.Shipping.status;
            }
        }

        private void btnConfirm_ButtonClick(object sender, EventArgs e)
        {
            btnConfirm.ShowDropDown();

        }

        private void btnConfirmOk_Click_1(object sender, EventArgs e)
        {
            try
            {
                int BillId = Common.StringToInt(tMain.Rows[0]["id"].ToString());
                VerifyBillResult vbResult = BaseDataProxy.VerifyBill(BillPrefix, BillId, SysLoginUserInfo.UserId, true);
                MessageBox.Show(vbResult.Message);
                if (vbResult.Pass)
                {
                    //UpdateStatus(BillId);
                    //EditStatus = Common.BillOperateType.View;
                    //SetControlsStatus(false);
                    //gvDetail.Refresh();
                    OpenBill(Common.StringToInt(tMain.Rows[0]["id"].ToString()));
                }
            }
            catch
            {
            }
        }

        private void btnConfirmCancel_Click_1(object sender, EventArgs e)
        {
            try
            {
                int BillId = Common.StringToInt(tMain.Rows[0]["id"].ToString());
                VerifyBillResult vbResult = BaseDataProxy.VerifyBill(BillPrefix, BillId, SysLoginUserInfo.UserId, false);
                MessageBox.Show(vbResult.Message);
                if (vbResult.Pass)
                {
                    //UpdateStatus(BillId);
                    //EditStatus = Common.BillOperateType.Update;
                    //SetControlsStatus(true);
                    //gvDetail.Refresh();
                    OpenBill(Common.StringToInt(tMain.Rows[0]["id"].ToString()));
                }
            }
            catch
            {
            }
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            //
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void traderSelector_SelectorClick(object sender, EventArgs e)
        {
            if ((EditStatus != Common.BillOperateType.Add) & (EditStatus != Common.BillOperateType.Update))
            {
                return;
            }

            TraderFrm frm = new TraderFrm();
            frm.Text = "选择供应商";
            frm.SearchSupplierMode(); // .SetTraderAsSupplier();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                edtTrader.SetSelected(frm.SelectorItem);
                tMain.Rows[0]["trader"] = Common.StringToInt(frm.SelectorItem.Value);
            }
        }

        private void UpdateBizManList(int DepartmentId)
        {
            XUsers = BaseDataProxy.FindUsers(DepartmentId, "", "");

            //XUsers.copy order by user name
            //刷新部门对应业务员
            IEnumerable<XUser> query = XUsers.OrderBy(XUser => XUser.User.name);
            edtBusinessman.Items.Clear();
            if (query.Count() == 0)
                return;
            foreach (XUser rc in query)
            {
                edtBusinessman.Items.Add(rc.User);
            }
            edtBusinessman.DisplayMember = "name";
            edtBusinessman.ValueMember = "id";
        }

        private void departmentUTextBox_SelectorClick(object sender, EventArgs e)
        {
            if ((EditStatus != Common.BillOperateType.Add) & (EditStatus != Common.BillOperateType.Update))
            {
                return;
            }

            DeptFrm frm = new DeptFrm();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                departmentUTextBox.ValueType = Selector.NodeValueType.Name;
                departmentUTextBox.SetSelected(frm.SelectorItem);

                tMain.Rows[0]["department"] = Common.StringToInt(frm.SelectorItem.Value);
                UpdateBizManList(Common.StringToInt(frm.SelectorItem.Key));
            }
        }

        private void businessmanUTextBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            //IEnumerable<XUser> query = XUsers.OrderBy(XUser => XUser.User.name);
            //string sBizManName = edtBusinessman.Text;
            //IEnumerable<XUser> rDp = from dp in XUsers
            //                         where dp.User.name == sBizManName
            //                         select dp;

            //tMain.Rows[0]["businessman"] = rDp.First().User.id;
        }

        private void btnSelectProduction_Click(object sender, EventArgs e)
        {
            FindBillFrm frm = new FindBillFrm();
            frm.AllowMulitSelect = false;
            frm.SelectBillType = GRWL.BZSC.Common.EnumCommon.BillType.SCD;
            //frm.BillPrefix = "SCSH";
            frm.Text = "选单(来自生产单)";
            frm.status = "已批";

            frm.ShowDialog();

            if (frm.DialogResult == DialogResult.OK)
            {
                if (frm.SelectedItems != null)
                {
                    for (int i = this.gvDetail.Rows.Count - 1; i >= 0; i--)
                    {
                        gvDetail.Rows.RemoveAt(i);
                    }
                    QProduction qpro = OTConverter.ConvertToObject<QProduction>(frm.SelectedItems);

                    BillFromProduction(qpro.Id);
                }
            }
        }

        private void BillFromProduction(int BillId)
        {
            //XProduction xMain = BaseDataProxy.GetXProduction(BillId);
            XPrdnDetail[] xDetials1 = BaseDataProxy.GetXPrdnDetails(BillId);

            tDetail.Clear();
            if ((xDetials1 != null) && (xDetials1.Count() > 0))
            {
                foreach (XPrdnDetail tbItem in xDetials1)
                {
                    DataRow dr = tDetail.NewRow();

                    dr["shipping"] = tMain.Rows[0]["id"];
                    dr["shippingCode"] = tMain.Rows[0]["code"];
                    if (tbItem.PrdnDetail.orderId != null)
                        dr["order"] = tbItem.PrdnDetail.orderId;
                    if (tbItem.PrdnDetail.orderDetailId != null)
                        dr["orderDetailId"] = tbItem.PrdnDetail.orderDetailId;
                    dr["orderCode"] = tbItem.PrdnDetail.orderCode;
                    dr["material"] = tbItem.PrdnDetail.material;
                    dr["MaterialCode"] = tbItem.PrdnDetail.materialCode;
                    dr["MaterialName"] = tbItem.MaterialName;
                    dr["Specs"] = tbItem.PrdnDetail.specs;
                    dr["Unit"] = tbItem.Unit;
                    if (tbItem.PrdnDetail.finishNum == null)
                        dr["shippingNum"] = 0;
                    else
                        dr["shippingNum"] = tbItem.PrdnDetail.finishNum;
                    dr["prevId"] = tbItem.PrdnDetail.prdn;
                    dr["prevCode"] = tbItem.PrdnDetail.prdnCode;
                    dr["prevType"] = BZSC.Common.EnumCommon.BillType.SCD.ToString();
                    dr["prevDetailId"] = tbItem.PrdnDetail.id;
                    tDetail.Rows.Add(dr);
                }
            }
        }

        private void edtTrader_SelectorTextUpdate(object sender, EventArgs e)
        {
            TB_Trader[] datas = BaseDataProxy.FindTraders(null, true, null, null, null, (sender as Selector).GetComboBoxText());
            (sender as Selector).ReBindComboBox<TB_Trader>(datas, "id", "name", "code");

        }

    }
}
